<!-- 发布信息 -->
<template>
	<view class="page-content">
		<view class="scroll-Y pagebt75">
			<u-navbar title="新增派生信息" :background="background"></u-navbar>

			<u-form :model="formData" ref="uForm">
				<view class="m-3 py-4 px-3 form rounded-8">
					<view class="font-md font-weight text-main">项目基本信息</view>
					<u-form-item
						class="required projectNameScroll"
						label="项目名称"
						label-position="top"
						:border-bottom="false"
					>
						<u-input border height="80" v-model="formData.projectName" placeholder="请输入项目名称" />
					</u-form-item>
					<u-form-item
						class="required infoTypeScroll"
						label="信息类型"
						label-position="top"
						:border-bottom="false"
					>
						<hpy-form-select
							:dataList="infoTypeList"
							text="label"
							name="value"
							v-model="formData.infoType"
							title="请选择信息类型"
							hideBorder
							disabled="true"
							hideArrow
						/>
					</u-form-item>

					<u-form-item
						class="required projectStageScroll"
						label="项目阶段"
						label-position="top"
						:border-bottom="false"
					>
						<hpy-form-select
							:dataList="projectPhase2List"
							text="label"
							name="value"
							v-model="formData.projectStage"
							title="请选择项目阶段"
							hideBorder
						/>
					</u-form-item>
					<u-form-item
						class="required projectAddressNameScroll"
						label="项目地址"
						label-position="top"
						:border-bottom="false"
					>
						<view class="position-relative w-100 ">
							<u-input
								border
								height="80"
								v-model="formData.projectAddressName"
								placeholder="请输入项目地址"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-calendar-todo-fill text-primary"
								@click="getAddressFn"
							></text>
						</view>
					</u-form-item>
					<u-form-item
						class="required outputScaleScroll"
						label="预计产值规模"
						label-position="top"
						:border-bottom="false"
					>
						<u-input border height="80" v-model="formData.outputScale" placeholder="请输入预计产值规模" />
					</u-form-item>
					<u-form-item label="项目备注" label-position="top" :border-bottom="false">
						<u-input
							border
							height="120"
							type="textarea"
							v-model="formData.projectRemark"
							placeholder="请输入项目备注"
						/>
					</u-form-item>
				</view>

				<view class="m-3 py-4 px-3 form rounded-8" v-if="formData.projectStage == 'BidTender'">
					<view class="font-md font-weight text-main">招标信息</view>
					<u-form-item
						class="required qualificationsScroll"
						label="资质要求"
						label-position="top"
						:border-bottom="false"
					>
						<u-input border height="80" v-model="formData.qualifications" placeholder="请输入资质要求" />
					</u-form-item>

					<u-form-item
						class="required tenderClosingDateScroll"
						label="招标获取截止时间"
						label-position="top"
						:border-bottom="false"
					>
						<view class="position-relative w-100 " @click="openexpireDatePicker">
							<u-input
								border
								height="80"
								v-model="formData.tenderClosingDate"
								placeholder="请输入招标获取截止时间"
								@click="openexpireDatePicker"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-xiajiantou u-font-28 text-tips"
							></text>
						</view>
					</u-form-item>

					<u-form-item
						class="required deadlineForBiddingScroll"
						label="招标截止时间"
						label-position="top"
						:border-bottom="false"
					>
						<view class="position-relative w-100 " @click="openexpireDatePicker2">
							<u-input
								border
								height="80"
								v-model="formData.deadlineForBidding"
								placeholder="请输入招标截止时间"
								@click="openexpireDatePicker2"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-xiajiantou u-font-28 text-tips"
							></text>
						</view>
					</u-form-item>

					<u-form-item label="资金来源" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.fundingSource" placeholder="请输入资金来源" />
					</u-form-item>
					<u-form-item label="工程规模" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.projectScale" placeholder="请输入工程规模" />
					</u-form-item>
					<u-form-item label="工期要求" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.durationRequired" placeholder="请输入工期要求" />
					</u-form-item>
					<u-form-item label="招标范围" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.tenderScope" placeholder="请输入招标范围" />
					</u-form-item>
					<u-form-item label="招标控制价" label-position="top" :border-bottom="false">
						<u-input
							border
							height="80"
							type="number"
							v-model="formData.tenderControlPrice"
							placeholder="请输入招标控制价"
						/>
					</u-form-item>
					<u-form-item label="保证金金额" label-position="top" :border-bottom="false">
						<u-input
							border
							height="80"
							type="number"
							v-model="formData.bond"
							placeholder="请输入保证金金额"
						/>
					</u-form-item>

					<u-form-item label="缴纳保证金截止时间" label-position="top" :border-bottom="false">
						<view class="position-relative w-100 " @click="openexpireDatePicker3">
							<u-input
								border
								height="80"
								v-model="formData.bondEndTime"
								placeholder="请输入缴纳保证金截止时间"
								@click="openexpireDatePicker3"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-xiajiantou u-font-28 text-tips"
							></text>
						</view>
					</u-form-item>
				</view>

				<view class="m-3 py-4 px-3 form rounded-8">
					<view class="font-md font-weight text-main">项目方</view>
					<u-form-item
						class="required ownerCompanyNameScroll"
						label="业主方公司名称"
						label-position="top"
						:border-bottom="false"
					>
						<u-input
							border
							height="80"
							v-model="formData.ownerCompanyName"
							placeholder="请输入业主方公司名称"
						/>
					</u-form-item>
					<u-form-item label="施工方公司名称" label-position="top" :border-bottom="false">
						<u-input
							border
							height="80"
							v-model="formData.constructionName"
							placeholder="请输入施工方公司名称"
						/>
					</u-form-item>
				</view>

				<view class="m-3 py-4 px-3 form rounded-8">
					<view class="u-flex u-row-between">
						<view class="font-md font-weight text-main">指派目标企业</view>

						<view @click="addTargetFn" class="iconfont icon-jia text-primary font-lg"></view>
					</view>
					<view class="pb-2 cropanyBox" v-for="(item, index) in formData.busiIndustryAssignList" :key="index">
						<u-form-item
							class="required position-relative busiIndustryAssignListScroll"
							label="产业标记"
							label-position="top"
							:border-bottom="false"
						>
							<!-- @input="e => inputChange(e, item, index)" -->
							<hpy-form-select
								:dataList="getAvailableIndustrialMarks(index)"
								text="name"
								name="dictId"
								v-model="item.industryId"
								title="请选择产业标记"
								@change="e => changeMarkFn(e, index)"
								hideBorder
							/>
							<view
								v-if="index != 0"
								class="position-absolute top-6 right-0 iconfont icon-shanchu2 font-md text-error font-weight"
								@click="delMarksFn(index)"
							></view>
						</u-form-item>
						<!-- @change="e => queryBureauFn((e, index))" -->
						<u-form-item label="指派目标企业" label-position="top" :border-bottom="false">
							<view class="bg-grey rounded-8 w-100 px-2 py">
								<view class="bb inputHight font-sm text-tips" @click="addCorpFn(index)">
									<text class="iconfont icon-jia text-primary pr-2"></text>
									添加新企业
								</view>
								<view class="bb inputHight " v-for="(i, x) in item.busiIndustryCompanyList" :key="x">
									<view class="d-flex j-sb a-center">
										<view class="font-sm text-tips">{{ i.companyName }}</view>
										<view
											class="iconfont icon-shanchu text-error"
											@click="delcropFn(index, i)"
										></view>
									</view>
								</view>
							</view>
						</u-form-item>
					</view>
				</view>
			</u-form>
		</view>
		<view class="subarea">
			<button class="warningBnt btn-cancel font-weight-100" @click="hanglgCancelFn">取 消</button>
			<button class="primaryBnt btn-submit font-weight-100" @click="hanglgSubmitFn">提 交</button>
		</view>

		<amap-choose ref="amapChoose" :keyMap="keyMap" @placeChoose="placeChoose"></amap-choose>

		<atl-map
			v-if="showMap"
			:longitude="formData.longitude"
			:latitude="formData.latitude"
			:mapKey="mapKey"
			:mapType="mapType"
			@confirm="confirmMap"
			@changeMarker="changeMarker"
		>
			<template v-slot:content>
				<view style="position: absolute; bottom: 0;width: 100%;height: 42rpx; background-color: white;"></view>
			</template>
		</atl-map>
    
		<datetime-picker
			ref="myPicker"
			@submit="handlexpireDatePicker"
			:start-year="2000"
			:end-year="2099"
			:time-init="Date.now()"
			:time-hide="[true, true, true, false, false, false]"
			:time-label="['年', '月', '日', '时', '分', '秒']"
		/>
		<datetime-picker
			ref="myPicker2"
			@submit="handlexpireDatePicker2"
			:start-year="2000"
			:end-year="2099"
			:time-init="Date.now()"
			:time-hide="[true, true, true, false, false, false]"
			:time-label="['年', '月', '日', '时', '分', '秒']"
		/>
		<datetime-picker
			ref="myPicker3"
			@submit="handlexpireDatePicker3"
			:start-year="2000"
			:end-year="2099"
			:time-init="Date.now()"
			:time-hide="[true, true, true, false, false, false]"
			:time-label="['年', '月', '日', '时', '分', '秒']"
		/>
	</view>
</template>
<script>
import { infoTypeList, projectPhaseList, projectPhase2List } from '@/utils/data.js';
import amapChoose from '@/components/amap-choose/amap-choose.nvue';
import atlMap from '@/components/atl-map/atl-map.vue';
import {
	getDictByParentId,
	addBusiInfoData,
	updateBusiInfoData,
	getbusiInfoData,
	getPlaceByAddress,
	getPlaceByLocation
} from '@/api/apis.js';
export default {
	components: { amapChoose, atlMap },
	data() {
		return {
			background: {
				backgroundColor: '#fff'
			},

			formData: {
				projectName: '',
				infoType: '',
				projectStage: '',
				province: '',
				provinceCode: '',
				city: '',
				cityCode: '',
				projectAddressName: '',
				longitude: '',
				latitude: '',
				outputScale: '',
				projectRemark: '',
				ownerCompanyName: '',
				constructionName: '',
				busiIndustryAssignList: [
					{
						industryId: '',
						industryName: '',
						busiIndustryCompanyList: []
					}
				],
				qualifications: '',
				tenderClosingDate: '',
				deadlineForBidding: '',
				fundingSource: '',
				projectScale: '',
				durationRequired: '',
				tenderScope: '',
				tenderControlPrice: null,
				bond: null,
				bondEndTime: ''
			},
			keyMap: '5dcmOzZFnXaVEwEgMw1wQxoXjOaI8GXk',
			showMap: false,
			mapKey: '6ix3cNjS7kmLf8i4oMiAYpWTzkNaq3gj', //百度地图
			mapType: 'bmap', // tmap bmap amap
			initLocation: '',
			infoTypeList, //信息类型
			projectPhaseList, //项目阶段
			projectPhase2List, //项目阶段
			industrialMarkList: [],
			certificateTypeList: [],
			selectedIndustryIds: [] // 用于跟踪已经选择的产业标记ID
		};
	},
	onLoad() {
		this.getDictFn();
		uni.$on('globleEvent', rel => {
			this.formData.busiIndustryAssignList[rel.index].busiIndustryCompanyList = [];
			rel.data.forEach(x => {
				if (this.formData.busiIndustryAssignList[rel.index].busiIndustryCompanyList) {
					this.formData.busiIndustryAssignList[rel.index].busiIndustryCompanyList.push(x);
				}
			});
		});
		if (this.$Route.query.busiInfoId) {
			this.getbusiInfoDataFn(this.$Route.query.busiInfoId);
		}
		if (this.$Route.query.index || this.$Route.query.index == 0) {
			let formDataStorage = uni.getStorageSync('formDataStorage') || [];
			this.formData = formDataStorage[this.$Route.query.index];
		}
	},

	methods: {
		changeMarkFn(e, index) {
			this.formData.busiIndustryAssignList[index].busiIndustryCompanyList = [];
			const selectedId = this.formData.busiIndustryAssignList[index].industryId;
			this.formData.busiIndustryAssignList[index].industryName = e.data.name;
			// 检查当前选择的产业标记是否与之前选择的不同
			const previousSelection = this.selectedIndustryIds[index];
			if (selectedId && previousSelection !== selectedId && this.selectedIndustryIds.includes(selectedId)) {
				// 如果当前选择的是一个新的且已被之前选择器选中的产业标记，则显示提示并重置选择
				uni.showToast({ title: '该产业标记已被选择，请选择其他标记', icon: 'none' });
				this.formData.busiIndustryAssignList[index].industryId = '';
			} else {
				// 如果当前选择的是一个新的或未被选中的产业标记，则更新记录
				this.selectedIndustryIds[index] = selectedId;
			}
		},

		getAvailableIndustrialMarks(currentIndex) {
			// 返回当前选择器可用的产业标记列表（排除已选中的）
			return this.industrialMarkList.filter(mark => {
				// 检查产业标记是否已被之前的选择器选中
				return !this.selectedIndustryIds.slice(0, currentIndex).includes(mark.value);
			});
		},
		//删除指派目标企业
		delMarksFn(index) {
			this.formData.busiIndustryAssignList.splice(index, 1);
			this.selectedIndustryIds.splice(index, 1);
		},
		//地图选址获取位置
		getAddressFn() {
			// #ifdef H5
			this.openMap();
			// #endif
			// #ifndef H5
			this.showMap = true;
			// #endif
		},
		//打开地图
		openMap() {
			this.$refs.amapChoose.innerUser(this.initLocation);
		},

		//确认地图
		placeChoose(res) {
			this.formData.projectAddressName = res.address;
			this.formData.longitude = res.longitude;
			this.formData.latitude = res.latitude;
			this.getNowPlace(this.formData.longitude, this.formData.latitude);
		},
		//根据经纬度查询地址
		getNowPlace(lng, lat) {
			getPlaceByLocation({
				lat: lat,
				lng: lng
			}).then(res => {
				if (res.code == 10000) {
					let result = res.data.result;
					this.formData.province = result.addressComponent.province;
					this.formData.city =
						result.addressComponent.city === '北京市' ||
						result.addressComponent.city === '天津市' ||
						result.addressComponent.city === '上海市' ||
						result.addressComponent.city === '重庆市'
							? result.addressComponent.district
							: result.addressComponent.city;
				} else {
					this.$u.toast(res.msg);
				}
			});
		},
		// 获取产业标记
		getDictFn() {
			getDictByParentId({
				parentId: 'COMPANY_SERVICE'
			}).then(res => {
				if (res.code == 10000) {
					this.industrialMarkList = res.data;
					this.industrialMarkList.forEach(x => {
						this.$set(x, 'label', x.name);
						this.$set(x, 'value', x.dictId);
					});
				} else {
					this.$u.toast(res.msg);
				}
			});
		},
		//添加新公司
		addCorpFn(index) {
			if (!this.formData.busiIndustryAssignList[index].industryId) {
				this.$u.toast('请选择产业标记');
				return false;
			}
			this.$Router.push({
				path: '/detailPages/pages/joinCompany/index',
				query: {
					index: index,
					industryId: this.formData.busiIndustryAssignList[index].industryId,
					busiIndustryCompanyList: this.formData.busiIndustryAssignList[index].busiIndustryCompanyList.map(
						item => item.companyId
					)
				}
			});
		},
		//添加目标企业
		addTargetFn() {
			this.formData.busiIndustryAssignList.push({
				industryId: '',
				industryName: '',
				busiIndustryCompanyList: []
			});
		},

		//删除目标企业
		delcropFn(index, i) {
			this.formData.busiIndustryAssignList[index].busiIndustryCompanyList.splice(i, 1);
		},
		//取消
		hanglgCancelFn() {
			this.$Router.back();
		},
		//提交
		hanglgSubmitFn() {
			if (this.validRuleFn()) {
				if (this.$Route.query.index || this.$Route.query.index == 0) {
					let formDataStorage = uni.getStorageSync('formDataStorage') || [];
					formDataStorage[this.$Route.query.index] = this.formData;
					uni.setStorage({
						key: 'formDataStorage',
						data: formDataStorage
					});
					this.$Router.back();
				} else {
					let formDataStorage = uni.getStorageSync('formDataStorage') || [];
					formDataStorage.push(this.formData);
					uni.setStorage({
						key: 'formDataStorage',
						data: formDataStorage
					});
					this.$Router.back();
				}
			}
		},
		//校验
		validRuleFn() {
			if (this.formData.projectName == '') {
				this.$u.toast('请输入项目名称');
				uni.pageScrollTo({
					selector: '.projectNameScroll',
					duration: 300
				});
				return false;
			}
			if (this.formData.infoType == '') {
				this.$u.toast('请选择信息类型');
				uni.pageScrollTo({
					selector: '.infoTypeScroll',
					duration: 300
				});
				return false;
			}
			if (this.formData.projectStage == '') {
				this.$u.toast('请选择项目阶段');
				uni.pageScrollTo({
					selector: '.projectStageScroll',
					duration: 300
				});
				return false;
			}
			if (this.formData.projectAddressName == '') {
				this.$u.toast('请选择项目地址');
				uni.pageScrollTo({
					selector: '.projectAddressNameScroll',
					duration: 300
				});
				return false;
			}
			if (this.formData.outputScale == '') {
				this.$u.toast('请输入预计产值规模');
				uni.pageScrollTo({
					selector: '.outputScaleScroll',
					duration: 300
				});
				return false;
			}

			if (this.formData.projectStage == 'BidTender') {
				if (this.formData.qualifications == '') {
					this.$u.toast('请输入资质要求');
					uni.pageScrollTo({
						selector: '.qualificationsScroll',
						duration: 300
					});
					return false;
				}
				if (this.formData.tenderClosingDate == '') {
					this.$u.toast('请输入招标获取截止时间');
					uni.pageScrollTo({
						selector: '.tenderClosingDateScroll',
						duration: 300
					});
					return false;
				}
				if (this.formData.deadlineForBidding == '') {
					this.$u.toast('请输入招标截止时间');
					uni.pageScrollTo({
						selector: '.deadlineForBiddingScroll',
						duration: 300
					});
					return false;
				}
			}

			if (this.formData.ownerCompanyName == '') {
				this.$u.toast('请输入业主方公司名称');
				uni.pageScrollTo({
					selector: '.ownerCompanyNameScroll',
					duration: 300
				});
				return false;
			}

			for (let i of this.formData.busiIndustryAssignList) {
				if (i.industryId == '') {
					this.$u.toast('请选择产业标记');
					uni.pageScrollTo({
						selector: '.busiIndustryAssignListScroll',
						duration: 300
					});
					return;
				}
			}

			return true;
		},
		//获取项目详情
		getbusiInfoDataFn(id) {
			getbusiInfoData({
				busiInfoId: id
			}).then(res => {
				if (res.code == 10000) {
					this.formData = res.data;
					this.formData.infoType = 'ProfessionRelevance';
					this.formData.infoTypeName = '产业链关联';
					this.formData.busiIndustryAssignList.forEach(i => {
						i.busInfoTrack = {};
						i.busiIndustryAssignId = '';
						i.busiIndustryCompanyList = [];
						i.feedbackEndDate = '';
						i.forewarningEndDate = '';
						i.industryId = '';
						i.industryName = '';
						i.receiveStatus = '';
						i.receiveStatusName = '';
					});
				} else {
					this.$u.toast(res.msg);
				}
			});
		},

		changeMarker(e) {
			const { latitude, longitude } = e;
		},
		submit(e) {
			console.log(e, '6');
		},
		confirmMap(e) {
			if (e) {
				this.formData.longitude = e.longitude;
				this.formData.latitude = e.latitude;
				this.formData.projectAddressName = e.address;
			}
			this.showMap = false;
		},
		openexpireDatePicker() {
			this.$refs.myPicker.show();
		},
		handlexpireDatePicker(e) {
			this.formData.tenderClosingDate = `${e.year}-${e.month}-${e.day}`;
		},
		openexpireDatePicker2() {
			this.$refs.myPicker2.show();
		},
		handlexpireDatePicker2(e) {
			this.formData.deadlineForBidding = `${e.year}-${e.month}-${e.day}`;
		},
		openexpireDatePicker3() {
			this.$refs.myPicker3.show();
		},
		handlexpireDatePicker3(e) {
			this.formData.bondEndTime = `${e.year}-${e.month}-${e.day}`;
		}
	}
};
</script>

<style lang="scss" scoped>
.form {
	background-color: #fff;
	::v-deep .select-picker {
		width: 628rpx !important;
	}
	.inputHight {
		height: 40px;
	}
	.cropanyBox {
		border-bottom: 1px solid #f3f5f8;
		.bb :last-child {
			border-bottom: none !important;
		}
	}
}
</style>
